package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.SignSummaryListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SignSummaryOriginal;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 考勤汇总列表
 * 开发者: HuXiaoDan
 * 日期: 2016/12/14 16:54
 */
public class SignSummaryListFragment extends BaseListFragment {

  private static final int REQUIRE_QUERY = 0;
  private SignSummaryListAdapter mAdapter;
  private CurrentUser mUser;
  private int mPage = 1;

  private TextView mNameTv;
  private TextView mStartDateTv;
  private TextView mEndDateTv;
  private String mJobNames;//被考勤人
  private String mJobNos;//被考勤人job
  private String mBegindate;//开始时间
  private String mEnddate;//结束时间
  private String mTypeName;//打卡范围
  private String mTypeCode;//打卡范围
  private String rangeDeptCodes;//部门拼接
  private String arrJobNames;//人员拼接

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    mUser = CurrentUser.newInstance(getActivity());
    //初始化默认查询条件
    mJobNames = mUser.getRealName();
    mJobNos = mUser.getJobNumber();
    mBegindate = MyDateUtil.getFirstDay();
    mEnddate = MyDateUtil.parseTimeToString(new Date(), MyDateUtil.TYPE_DATE);
    mTypeName = "全部";
    mTypeCode = "";
    rangeDeptCodes = "";
    arrJobNames = mJobNames;
    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header = getLayoutInflater(savedInstanceState).inflate(R.layout.header_sign, null, false);
    header.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View v) {
        startQuery();
      }
    });
    mNameTv = (TextView) header.findViewById(R.id.tv_name_signHeader);
    mStartDateTv = (TextView) header.findViewById(R.id.tv_startDate_signHeader);
    mEndDateTv = (TextView) header.findViewById(R.id.tv_endDate_signHeader);
    updateHeader();
    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      case R.id.menu_item_query:
        //                mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        //                mPage = 1;
        //                volleyPost();
        //                mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        startQuery();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public String getUrl() {
    return ApiConst.URL_ATTTENDANCE_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("curPage", mPage + "");
    params.put("pageSize", "20");
    params.put("type", "mobile");
    params.put("memberCode", mUser.getMemberCode());
    params.put("arrJobNames", arrJobNames);//多选人名neme
    params.put("rangeDeptCodes", rangeDeptCodes);//多选部门code
    params.put("beginrecordDate", mBegindate);
    params.put("endrecordDate", mEnddate);
    params.put("queryArea", mTypeCode);//打卡范围code
    return params;
  }

  private void startQuery() {
    Intent intent = new Intent(getActivity(), AttendanceSummaryQueryActicity.class);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_STAFF_NAME, mJobNames);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_JOB_NUMBER, mJobNos);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_BEGIN_DATE, mBegindate);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_END_DATE, mEnddate);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_NAME, mTypeName);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_CODE, mTypeCode);
    intent.putExtra(AttendanceSummaryQueryFragment.VALUE_FROM,
        AttendanceSummaryQueryFragment.SIGN_SUMMARY);
    startActivityForResult(intent, REQUIRE_QUERY);
  }

  private void updateHeader() {
    mStartDateTv.setText(mBegindate);
    mEndDateTv.setText(mEnddate);
    mNameTv.setText(String.format("员工<%s>", mJobNames));
  }

  @Override public void resolveResponse(String json) {
    SignSummaryOriginal original = new Gson().fromJson(json, SignSummaryOriginal.class);
    ArrayList<SignSummaryOriginal.SignSummaryContent> rows =
        (ArrayList<SignSummaryOriginal.SignSummaryContent>) original.getRows();
    if (rows != null && rows.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(rows);
  }

  private void setAdapter(ArrayList<SignSummaryOriginal.SignSummaryContent> rows) {

    if (rows == null) {
      rows = new ArrayList<>();
    }
    if (mAdapter == null) {
      mAdapter = new SignSummaryListAdapter(getActivity(), rows);
      setListAdapter(mAdapter);
      return;
    }
    if (mPage == 1) {
      mAdapter.clear();
    }
    mAdapter.addAll(rows);
    mAdapter.notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    SignSummaryOriginal.SignSummaryContent content = mAdapter.getItem(position - 2);
    Intent i = new Intent(getActivity(), SignSummaryDetailActivity.class);
    i.putExtra(SignSummaryDetailFragment.EXTRA_VALUE, content);
    startActivity(i);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    PullToRefreshBase.Mode mode = refreshView.getCurrentMode();
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
      mPage = 1;
    }
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUIRE_QUERY && data != null) {
      mJobNames = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_STAFF_NAME);
      mJobNos = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_JOB_NUMBER);
      mBegindate = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_BEGIN_DATE);
      mEnddate = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_END_DATE);
      mTypeName = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_NAME);
      mTypeCode = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_CODE);
      LogUtil.i("mjobNos=="
          + mJobNos
          + ",mEnddate=="
          + mEnddate
          + ",mEnddate=="
          + mEnddate
          + ",mType=="
          + mTypeName);
      //mJobNos 中包含 " '"说明选择的是部门
      if (!TextUtils.isEmpty(mJobNos) && mJobNos.contains("'")) {
        arrJobNames = "";
        rangeDeptCodes = mJobNos;
      } else {
        arrJobNames = mJobNames;
        rangeDeptCodes = "";
      }
      updateHeader();
    }
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
    mPage = 1;
    volleyPost();
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    super.onActivityResult(requestCode, resultCode, data);
  }
}
